import 'dart:convert';
import 'dart:developer';

void tryCatch(Function? f) {
  try {
    f?.call();
  } catch (e, stack) {
    log('$e');
    log('$stack');
  }
}

class FFConvert {
  FFConvert._();

  static T? Function<T extends Object?>(dynamic value) convert = <T>(dynamic value) {
    if (value == null) {
      return null;
    }
    return json.decode(value.toString()) as T?;
  };
}

T? asT<T extends Object?>(dynamic value, [T? defaultValue]) {
  if (value is T) {
    return value;
  }
  try {
    if (value != null) {
      final String valueS = value.toString();
      if ('' is T) {
        return valueS as T;
      } else if (0 is T) {
        return int.parse(valueS) as T;
      } else if (0.0 is T) {
        return double.parse(valueS) as T;
      } else if (false is T) {
        if (valueS == '0' || valueS == '1') {
          return (valueS == '1') as T;
        }
        return (valueS == 'true') as T;
      } else {
        return FFConvert.convert<T>(value);
      }
    }
  } catch (e, stackTrace) {
    log('asT<$T>', error: e, stackTrace: stackTrace);
    return defaultValue;
  }

  return defaultValue;
}

class ProcessType {
  ProcessType({
    required this.id,
    required this.typeIndex,
    required this.typeCode,
    required this.typeName,
    required this.typeDesc,
    required this.nodeStatus,
    required this.enabled,
    this.createEmp,
    this.createTime,
    this.updateEmp,
    this.updateTime,
  });

  factory ProcessType.fromJson(Map<String, dynamic> jsonRes) => ProcessType(
        id: asT<int>(jsonRes['id'])!,
        typeIndex: asT<int>(jsonRes['typeIndex'])!,
        typeCode: asT<String>(jsonRes['typeCode'])!,
        typeName: asT<String>(jsonRes['typeName'])!,
        typeDesc: asT<String>(jsonRes['typeDesc'])!,
        nodeStatus: asT<int>(jsonRes['nodeStatus'])!,
        enabled: asT<int>(jsonRes['enabled'])!,
        createEmp: asT<String?>(jsonRes['createEmp']),
        createTime: asT<String?>(jsonRes['createTime']),
        updateEmp: asT<String?>(jsonRes['updateEmp']),
        updateTime: asT<String?>(jsonRes['updateTime']),
      );

  int id;
  int typeIndex;
  String typeCode;
  String typeName;
  String typeDesc;
  int nodeStatus;
  int enabled;
  String? createEmp;
  String? createTime;
  String? updateEmp;
  String? updateTime;

  @override
  String toString() {
    return jsonEncode(this);
  }

  Map<String, dynamic> toJson() => <String, dynamic>{
        'id': id,
        'typeIndex': typeIndex,
        'typeCode': typeCode,
        'typeName': typeName,
        'typeDesc': typeDesc,
        'nodeStatus': nodeStatus,
        'enabled': enabled,
        'createEmp': createEmp,
        'createTime': createTime,
        'updateEmp': updateEmp,
        'updateTime': updateTime,
      };

  ProcessType clone() => ProcessType.fromJson(asT<Map<String, dynamic>>(jsonDecode(jsonEncode(this)))!);
}
